package array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Solution_56 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(p -> p[0]));
        List<int[]> res = new ArrayList<>();
        for (int[] interval : intervals) {
            int m=res.size();
            if(m>0&&res.get(m-1)[1]>=interval[0])
                res.get(m-1)[1]=Math.max(interval[1],res.get(m-1)[1]);
            else
                res.add(interval);
        }
        return res.toArray(new int[res.size()][]);
    }
}
